package com.spring.boot.standard.admin.controller;

import java.io.InputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import com.spring.boot.standard.admin.common.beans.PageData;
import com.spring.boot.standard.admin.common.CommonController;
import com.spring.boot.standard.admin.common.beans.CommonResult;
import com.spring.boot.standard.admin.entity.Codebase;
import com.spring.boot.standard.admin.service.CodebaseService;

/**
 * @author qinhao
 * @since Tue Oct 12 16:24:28 CST 2021
 */
@RestController
@RequestMapping("/codebase")
@Api(value="学习库接口",tags={"codebase(学习库)接口"})
public class CodebaseController extends CommonController {
	
    @Autowired
    CodebaseService codebaseService;

	@ApiOperation(value = "获取分页数据" ,notes = "获取分页数据" )
	@ApiImplicitParams({
		@ApiImplicitParam(name = "key" ,value = "搜索关键字名称" , required = false, dataType = "String"),
		@ApiImplicitParam(name = "keywords" ,value = "搜索关键字内容" , required = false, dataType = "String"),
		@ApiImplicitParam(name = "searchtype" ,value = "我的和全部" , required = false, dataType = "String"),
		@ApiImplicitParam(name = "creator" ,value = "创建人" , required = false, dataType = "String")
	})
    @RequestMapping(value = "/pagedata", method = { RequestMethod.GET  })
    public PageData<Codebase> pagedata(Pageable pageable,String key,String keywords,String searchtype,String creator){
        return convertPage(codebaseService.findAll(pageable,new Object[]{key,keywords,searchtype,creator}));
    }

	@ApiOperation(value = "获取单条数据对象" ,notes = "获取单条数据对象")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType = "query",name = "id" ,value = "学习库ID" , required = true, dataType = "String")
	})
	@RequestMapping(value = "/singledata" ,method = { RequestMethod.GET })
	public Codebase singledata(Integer id){
		return codebaseService.findById(id);
	}

	@ApiOperation(value = "删除学习库", notes = "删除学习库" )
		@ApiImplicitParams({ @ApiImplicitParam(name = "ids", value = "ID拼接的字符串", required = true, dataType = "String")
	})
	@RequestMapping(value = "/delete" ,method = { RequestMethod.DELETE})
	public CommonResult delete(String ids) {
		try {
			String[] id_array = ids.split(",");
			for(String id:id_array){
				codebaseService.deleteById(Integer.parseInt(id));
			}
			cr = new CommonResult(true,0,null,"删除成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return cr;
	}

	@ApiOperation(value = "保存学习库", notes = "保存学习库,id列为空则为新增,不为空则为修改")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "Codebase",value = "学习库",required = false,dataType = "Codebase")
	})
	@RequestMapping(value = "/save" ,method = { RequestMethod.POST })
	public CommonResult save(Codebase codebase) {
		try {
			codebase.setCreateDate(new Timestamp(new Date().getTime()));
			codebaseService.save(codebase);
			cr = new CommonResult(true,0,null,"保存成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return   cr;
	}

	@ApiOperation(value = "阅读次数增加", notes = "阅读次数增加")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "testid",value = "主键",required = false,dataType = "String")
	})
	@RequestMapping(value = "/readShow" ,method = { RequestMethod.POST })
	public CommonResult readShow(Integer testid) {
		try {
			Codebase codebase = codebaseService.findById(testid);
			codebase.setReadNums(codebase.getReadNums()+1);
			codebaseService.save(codebase);
			cr = new CommonResult(true,0,null,"更新成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return   cr;
	}

	@ApiOperation(value = "导出数据", notes = "导出数据")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "key" ,value = "搜索关键字名称" , required = false, dataType = "String"),
		@ApiImplicitParam(name = "keywords" ,value = "搜索关键字内容" , required = false, dataType = "String")
	})
	@RequestMapping(value = "/exports", method = { RequestMethod.GET  })
	public ResponseEntity<byte[]> exports( Pageable pageable,String key,String keywords) {
		ResponseEntity<byte[]> entity = null;
	    String[] titleNameArray = {"标题内容","编码","编码内容","说明","类型","关键字","阅读次数","修改信息备注","创建人","创建时间","序号","是否置顶   0 否   1  是","得分"};
		String[] fieldNameArray = {"titlename","coding","codeContent","explains","codeType","keyWord","readNums","remark","creator","createDate","orderNum","isIsstick","score"};
		try {
			//根据条件获取数据
            List<Codebase> data = codebaseService.findAll(pageable,new Object[]{key,keywords}).getContent();
			//数据转换成流并导出
			InputStream is = super.exportExcelContent(data,titleNameArray,fieldNameArray);
			byte[] body = new byte[is.available()];
			is.read(body);
			HttpHeaders headers = new HttpHeaders();
			String exportFilename = new SimpleDateFormat("yyyyMMddhhmmssSSS").format(new Date()) + ".xls";
			headers.add("Content-Disposition", "attchement;filename=" + exportFilename);
			HttpStatus statusCode = HttpStatus.OK;
			entity = new ResponseEntity<byte[]>(body, headers, statusCode);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return entity;
	}

	@ApiOperation(value = "导入学习库", notes = "导入学习库")
    @RequestMapping(value = "/imports", method = { RequestMethod.POST })
	public CommonResult imports(@RequestParam("file") MultipartFile file) {
		int imp_num = 0;
		//如果文件不为空，写入上传路径
		try {
			if(!file.isEmpty()) {
				String[] fieldNameArray = {"titlename","coding","codeContent","explains","codeType","keyWord","readNums","remark","creator","createDate","orderNum","isIsstick","score"};
				List<Map<String,String>> list = super.getExcelContent(file, fieldNameArray);
                imp_num =  codebaseService.saveFromList(list);
				cr = new CommonResult(true,0,null,"导入成功，导入数据："+imp_num+"条！");
			} else {
				cr = new CommonResult(false,500,null,"文件上传失败！");
			}
		} catch (Exception e) {
			cr = new CommonResult(false,500,null,super.getPointOfException(e.getMessage()));
		}
		return  cr;
	}

}